#!/bin/bash

# 默认项目名
DEFAULT_PROJECT="my_pytorch_project"

# 提示用户输入项目名并验证输入
while true; do
  read -rp "请输入项目名称（默认：$DEFAULT_PROJECT）：" USER_INPUT
  if [ -z "$USER_INPUT" ]; then
	PROJECT_NAME="$DEFAULT_PROJECT"
	break
  fi

  # 使用正则模式校验输入
  if [[ "$USER_INPUT" =~ ^[a-zA-Z][a-zA-Z0-9_\-]{2,126}[a-zA-Z0-9]$ ]]; then
	PROJECT_NAME="$USER_INPUT"
	break
  else
	echo "无效的项目名称。请按照指定规则输入一个有效的名称。"
  fi
done

# 创建项目目录
mkdir -p "$PROJECT_NAME"
cd "$PROJECT_NAME"

# 创建src目录及文件
mkdir src

cat << EOF > src/main.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 主脚本占位符
print("你好，世界！")
EOF

cat << EOF > src/model.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import torch.nn as nn

class MyModel(nn.Module):
	def __init__(self):
		super().__init__()
		# TODO: 在此处定义您的模型架构

	def forward(self, x):
		# TODO: 实现前向传播
		pass
EOF

cat << EOF > src/data.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from torch.utils.data import Dataset

class MyDataset(Dataset):
	def __init__(self):
		# TODO: 初始化数据集参数并加载数据

	def __len__(self):
		# TODO: 返回数据集长度
		return 0

	def __getitem__(self, idx):
		# TODO: 实现从数据集中获取样本
		return None
EOF

cat << EOF > src/train.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import torch
from torch.optim import SGD
from model import MyModel
from data import MyDataset

def train():
	# TODO: 实现训练逻辑
	pass

if __name__ == '__main__':
	train()
EOF

cat << EOF > src/test.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import torch
from model import MyModel
from data import MyDataset

def test(model, dataloader):
	# TODO: 实现测试逻辑
	pass

if __name__ == '__main__':
	test(MyModel(), None)
EOF

# 创建Makefile
cat << EOF > Makefile
# $PROJECT_NAME项目的Makefile

.PHONY: all clean run train test requirements

# 构建目标
all: run

clean:
	rm -rf dist build *.egg-info
	find . -name "__pycache__" -type d -exec rm -rf {} +
	find . -name "*.pyc" -delete

run:
	python src/main.py

train:
	python src/train.py

test:
	python src/test.py

requirements:
	pip install --upgrade pip setuptools wheel
	pip install -r requirements.txt
EOF

echo "已成功使用基于Makefile的构建系统创建PyTorch项目'$PROJECT_NAME'。"